import { auth, mainInfo, subaccountInfo, login, logout } from '@/api';
import { getToken, setToken, removeAllCookies, removeAllLocalStorages } from '@/utils/storage';
import { Message, Notification } from 'element-ui';
import lang from '@/lang';

/*
 *  内容:     state数据规范
 *  命名规范:
 *           1、数据初始值必须为undefined
 *           2、数据不能存储在window.localStorage
 */

const user = {
  state: {
    /*
     *  内容:    接口相关信息
     *  命名规范: 驼峰
     */

    // token，接口必传参数（除了auth接口）
    token: getToken(),
    // isMainInfo，是否请求过mainInfo接口
    isMainInfo: undefined,

    /*
     *  内容:    根账户相关信息
     *  命名规范: 接口返回字段名（驼峰）
     */

    // id，根账户id(判断是否为登录状态)
    id: undefined,
    // name，根账户用户名
    name: undefined,
    // email，根账户邮箱
    email: undefined,
    // isBingEmail，根账户是否绑定邮箱，数字0或1
    isBingEmail: undefined,
    // tel，根账户手机号
    tel: undefined,
    // phoneVerify，根账户是否开启手机号登录验证，数字0或1
    phoneVerify: undefined,
    // googleCode，根账户谷歌验证码
    googleCode: undefined,
    // googleVerify，根账户是否开启谷歌验证，数字0或1
    googleVerify: undefined,
    // type，根账户是否显示邀请，3显示
    type: undefined,
    // login_type，登录方式 tel/email
    loginType: undefined,

    /*
     *  内容:    子账户相关信息
     *  命名规范: 'sub'+接口返回字段名（驼峰）
     */

    // subId，子账户id
    subId: undefined,
    // subCuid，子账户cuid
    subCuid: undefined,
    // subname，子账户用户名
    subName: undefined,
    // subAddress，子账户钱包地址
    subAddress: undefined,
    // subBalanceType，子账户结算方式
    subBalanceType: undefined,
    // subCoinType，子账户币种类型
    subCoinType: undefined,

    /*
     *  内容:    观察者相关信息
     *  命名规范: 'ob'+接口返回字段名（驼峰）
     */

    // obName，观察者名
    obName: undefined,
    // obAccessKey，保存了subaccountInfo通过上传access_key返回的access_key(判断是否为观察者状态)
    obAccessKey: undefined,
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      setToken(token.val, token.overTime);
      state.token = token.val;
    },
    SET_IS_MAIN_INFO: (state, val) => {
      state.isMainInfo = val;
    },
    SET_ID: (state, val) => {
      state.id = val;
    },
    SET_NAME: (state, val) => {
      state.name = val;
    },
    SET_EMAIL: (state, val) => {
      state.email = val;
    },
    SET_IS_BING_EMAIL: (state, val) => {
      state.isBingEmail = val;
    },
    SET_TEL: (state, val) => {
      state.tel = val;
    },
    SET_PHONE_VERIFY: (state, val) => {
      state.phoneVerify = val;
    },
    SET_GOOGLE_CODE: (state, val) => {
      state.googleCode = val;
    },
    SET_GOOGLE_VERIFY: (state, val) => {
      state.googleVerify = val;
    },
    SET_TYPE: (state, val) => {
      state.type = val;
    },
    SET_SUB_ID: (state, val) => {
      state.subId = val;
    },
    SET_SUB_CUID: (state, val) => {
      state.subCuid = val;
    },
    SET_SUB_NAME: (state, val) => {
      state.subName = val;
    },
    SET_SUB_ADDRESS: (state, val) => {
      state.subAddress = val;
    },
    SET_SUB_BALANCE_TYPE: (state, val) => {
      state.subBalanceType = val;
    },
    SET_SUB_COIN_TYPE: (state, val) => {
      state.subCoinType = val;
    },
    SET_OB_NAME: (state, val) => {
      state.obName = val;
    },
    SET_OB_ACCESS_KEY: (state, val) => {
      state.obAccessKey = val;
    },
    SET_LOGIN_TYPE: (state, val) => {
      state.loginType = val;
    },
    CLEAR_ALL: (state) => {
      removeAllCookies();
      removeAllLocalStorages('language');
      Object.keys(state).forEach((val) => {
        state[val] = undefined;
      });
    },
  },
  actions: {
    Auth({ commit }) {
      return new Promise((resolve, reject) => {
        auth({
          app_name: 'dragonpool_app',
          app_password: 'Dpool_secret',
          app_time: new Date().getTime().toString().slice(0, -3),
        }).then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            commit('SET_TOKEN', {
              val: data.token,
              overTime: data.over_time,
            });
            resolve();
          } else {
            reject();
          }
        }).catch(() => {
          reject();
        });
      });
    },
    MainInfo({ commit }) {
      return new Promise((resolve, reject) => {
        mainInfo().then((response) => {
          commit('SET_IS_MAIN_INFO', true);
          if (response.data.status === 1) {
            const data = response.data.data;
            commit('SET_ID', data.id);
            commit('SET_NAME', data.name);
            // 是否开启谷歌验证
            commit('SET_GOOGLE_VERIFY', parseInt(data.google_verify, 10));
            // 是否之前开启过谷歌验证
            commit('SET_GOOGLE_CODE', data.google_code);
            // 是否已绑定邮箱
            commit('SET_IS_BING_EMAIL', parseInt(data.is_bing_email, 10));
            // 存储手机
            commit('SET_TEL', data.tel);
            // 存储邮箱
            commit('SET_EMAIL', data.email);
            // type=3 显示邀请
            commit('SET_TYPE', data.type);
            // 是否开启了手机验证码登录 0未开启 1 =已开启
            commit('SET_PHONE_VERIFY', parseInt(data.phone_verify, 10));
            // login_type，登录方式
            commit('SET_LOGIN_TYPE', data.login_type);
            if (data.first_sub) {
              commit('SET_SUB_ID', data.first_sub.id);
              commit('SET_SUB_BALANCE_TYPE', data.first_sub.balance_type);
              // 存储币种
              commit('SET_SUB_COIN_TYPE', data.first_sub.coin_type);
              commit('SET_SUB_CUID', data.first_sub.cuid);
              commit('SET_SUB_NAME', data.first_sub.name);
              // 存储账号钱包地址
              commit('SET_SUB_ADDRESS', data.first_sub.address);
            }
          } else if (response.data.status === -1) {
            // 根账户相关信息
            commit('SET_ID', undefined);
            commit('SET_NAME', undefined);
            commit('SET_EMAIL', undefined);
            commit('SET_IS_BING_EMAIL', undefined);
            commit('SET_TEL', undefined);
            commit('SET_PHONE_VERIFY', undefined);
            commit('SET_GOOGLE_CODE', undefined);
            commit('SET_GOOGLE_VERIFY', undefined);
            commit('SET_TYPE', undefined);
            // 子账户相关信息
            commit('SET_SUB_ID', undefined);
            commit('SET_SUB_CUID', undefined);
            commit('SET_SUB_NAME', undefined);
            commit('SET_SUB_ADDRESS', undefined);
            commit('SET_SUB_BALANCE_TYPE', undefined);
            commit('SET_SUB_COIN_TYPE', undefined);
            commit('SET_LOGIN_TYPE', undefined);
          }
          resolve(response);
        }).catch((error) => {
          reject(error);
        });
      });
    },
    AccessKey({ commit }, accessKey) {
      return new Promise((resolve, reject) => {
        subaccountInfo({
          access_key: accessKey,
        }).then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            commit('SET_OB_ACCESS_KEY', accessKey);
            commit('SET_OB_NAME', data.name);
            commit('SET_SUB_COIN_TYPE', data.coin_type);
            resolve();
          } else {
            commit('SET_OB_ACCESS_KEY', undefined);
            commit('SET_OB_NAME', undefined);
            commit('SET_SUB_COIN_TYPE', undefined);
            reject(response);
          }
        }).catch((error) => {
          commit('SET_OB_ACCESS_KEY', undefined);
          commit('SET_OB_NAME', undefined);
          commit('SET_SUB_COIN_TYPE', undefined);
          reject(error);
        });
      });
    },
    Login({ commit }, datas) {
      return new Promise((resolve, reject) => {
        login({
          email: datas.email,
          password: datas.password,
          code: datas.code,
          google_code: datas.google_code,
        }).then((response) => {
          if (response.data.status === 1) {
            const data = response.data.data;
            commit('SET_ID', data.id);
            commit('SET_NAME', data.name);
            // 是否开启谷歌验证
            commit('SET_GOOGLE_VERIFY', parseInt(data.google_verify, 10));
            // 是否之前开启过谷歌验证
            commit('SET_GOOGLE_CODE', data.google_code);
            // 是否已绑定邮箱
            commit('SET_IS_BING_EMAIL', parseInt(data.is_bing_email, 10));
            // 存储手机
            commit('SET_TEL', data.tel);
            // 存储邮箱
            commit('SET_EMAIL', data.email);
            // type=3 显示邀请
            commit('SET_TYPE', data.type);
            // 是否开启了手机验证码登录 0未开启 1 =已开启
            commit('SET_PHONE_VERIFY', parseInt(data.phone_verify, 10));
            // login_type，登录方式
            commit('SET_LOGIN_TYPE', data.login_type);
            // 判断有没有子账户
            if (data.first_sub.cuid) {
              commit('SET_SUB_ID', data.first_sub.id);
              commit('SET_SUB_ADDRESS', data.first_sub.address);
              commit('SET_SUB_BALANCE_TYPE', data.first_sub.balance_type);
              commit('SET_SUB_CUID', data.first_sub.cuid);
              commit('SET_SUB_NAME', data.first_sub.name);
              // 存储币种
              commit('SET_SUB_COIN_TYPE', data.first_sub.coin_type);
            }
            Notification({
              message: lang.t('login.success'),
              type: 'success',
              duration: 1000,
              showClose: false,
            });
            resolve(response);
          } else {
            Message.error(lang.t(`api.${response.data.errcode}`));
            reject(response);
          }
        }).catch((error) => {
          Message.error(lang.t('error.catchError'));
          reject(error);
        });
      });
    },
    Logout({ commit }) {
      return new Promise((reslove, reject) => {
        logout().then((response) => {
          if (response.data.status === 1) {
            commit('CLEAR_ALL');
            reslove(response);
          } else {
            reject(response);
          }
        }).catch((err) => {
          reject(err);
        });
      });
    },
  },
};

export default user;
